package com.xg.java.config;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.json.JSONObject;
import com.xg.java.service.ErrorService;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Component
public class ArchivesInterceptor implements HandlerInterceptor {

    @Resource
    private ErrorService errorService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("拦截后处理前");
        System.out.println("拦截了："+request.getRequestURI());
        response.setCharacterEncoding("UTF-8");
        if(null== StpUtil.getLoginIdByToken(request.getHeader("tokenValue"))){
            System.out.println("没有登录");
            PrintWriter out = null;
            out = response.getWriter();
            JSONObject JSONObj = new JSONObject();
            JSONObj.put("code","401");
            JSONObj.put("msg","请登录");
            JSONObj.put("data",null);
            out.write(JSONObj.toString());
            out.flush();
            return false;
        };
        System.out.println("登录成功");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
        System.out.println("拦截处理后，视图渲染前");
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        System.out.println("整个请求结束，渲染视图后");
    }
}
